<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>

        <el-card>
            <el-alert show-icon title="注意：只允许为第三级分类设置相关参数！" type="warning" :closable="false"></el-alert>
            <!-- 选择商品分类区域 -->
            <el-row class="cat_opt">
                <el-col>
                    <span>选择商品分类：</span>
                    <!-- 选择商品分类的级联选择框 -->
                    <el-cascader clearable expand-trigger="hover" :options="catelist" :props="cateProps"
                        v-model="selectedCateKeys" @change="handleChange">
                    </el-cascader>
                </el-col>
            </el-row>

            <el-tabs v-model="activeName" @tab-click="handleClick">
                <el-tab-pane label="动态参数" name="many">
                    <!-- 添加参数的按钮 -->
                    <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="openAddParamas">
                        添加参数</el-button>

                    <!-- 动态参数列表 -->
                    <el-table :data="manyData" border stripe>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag :key="i" v-for="(item, i) in scope.row.attr_vals" closable
                                    :disable-transitions="false" @close="handleClose(i, scope.row)">
                                    {{ item }}
                                </el-tag>
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                                    ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New
                                    Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index">
                        </el-table-column>
                        <el-table-column prop="attr_name" label="参数名称">
                        </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
                                <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeParams(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" size="mini" :disabled="isBtnDisabled" @click="openAddParamas">
                        添加参数</el-button>
                    <!-- 静态属性列表 -->
                    <el-table :data="onlyData" border stripe>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag :key="i" v-for="(item, i) in scope.row.attr_vals" closable
                                    :disable-transitions="false" @close="handleClose(i, scope.row)">
                                    {{ item }}
                                </el-tag>
                                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue"
                                    ref="saveTagInput" size="small" @keyup.enter.native="handleInputConfirm(scope.row)"
                                    @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New
                                    Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index">
                        </el-table-column>
                        <el-table-column prop="attr_name" label="参数名称">
                        </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <el-button size="mini" type="primary" icon="el-icon-edit">编辑</el-button>
                                <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>

         <!-- 添加参数对话框 -->
         <el-dialog :close-on-click-modal="false" title="添加参数" :visible.sync="addParamasVisible" width="50%"
            @close="addParamasClosed">
            <!-- 内容主体区域 -->
            <el-form :model="addParamasForm" :rules="addParamasFormRules" ref="addParamasFormRef" label-width="70px">
                <el-form-item label="参数名称" prop="attr_name" label-width="80px">
                    <el-input v-model="addParamasForm.attr_name"></el-input>
                </el-form-item>
            </el-form>
            <!-- 底部区域 -->
            <span slot="footer" class="dialog-footer">
                <el-button @click="addParamasVisible = false">取 消</el-button>
                <el-button type="primary" @click="addParamas">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>

export default {
    data() {
        return {
            catelist: [],
            // 级联选择框的配置对象
            cateProps: {
                value: "cat_id",
                label: "cat_name",
                children: "children",
            },
            selectedCateKeys: [],
            activeName: 'many',
            manyData: [],
            onlyData: [],
            addParamasVisible: false,
            addParamasForm: {
                attr_name: '',
            },
            addParamasFormRules: {
                attr_name: [
                    {required: true, message: '请输入参数名称', trigger:'blur'}
                ]
            }
        }
    },
    created() {
        this.getCateList()
    },
    methods: {
        async getCateList() {
            const res = await this.$http.get('categories', {
                params: { type: 3 },
            })
            if (res.status == 200) {
                this.catelist = res.data.data
            }
        },

        handleClick() {
            // tab点击切换的时候需要请求，但是如果没有选择分类的话，则不请求
            if (this.selectedCateKeys.length <= 0) {
                return
            }
            this.getParamsData()
        },

        handleChange() {
            if(this.cateId) {
                this.getParamsData()
            }
        },

        // 获取参数列表
        async getParamsData() {
            const res = await this.$http.get(`categories/${this.cateId}/attributes`, {
                params: { sel: this.activeName },
            })

            // console.log(res);

            if (res.status == 200) {
                // 包装一下数据，添加每一行单独的input输入框的显示隐藏和值的双向绑定，并且把attr_vals转成数组，方便循环渲染tag
                const data = res.data.data.map(item => ({
                    ...item,
                    attr_vals: item.attr_vals ? item.attr_vals.split(' ') : [],
                    inputVisible: false,
                    inputValue: ''
                }))

                // 切换tab的时候根据activeName的不同，挂载对应的数据
                if (this.activeName == 'many') {
                    this.manyData = data
                } else {
                    this.onlyData = data
                }
            }
        },

        // 失焦或者按enter键的时候需要添加tag，并且保存到后台数据中
        handleInputConfirm(row) {
            // console.log(row);
            // 如果输入的是空，则不做请求并还原状态
            if (row.inputValue.trim().length === 0) {
                row.inputVisible = false;
                row.inputValue = '';
                return
            }

            row.attr_vals.push(row.inputValue);

            // 发送请求保存
            this.saveAttrVals(row)

            // 重置input框的状态
            row.inputVisible = false;
            row.inputValue = '';

        },

        // 保存参数设置
        async saveAttrVals(row) {
            // 需要发起请求，保存这次操作
            const { data: res } = await this.$http.put(
                `categories/${this.cateId}/attributes/${row.attr_id}`,
                {
                    attr_name: row.attr_name,
                    attr_sel: row.attr_sel,
                    // 将数组拼接成以空格分割的字符串传递给后台
                    attr_vals: row.attr_vals.join(" "),
                }
            );

            if (res.meta.status !== 200) {
                return this.$message.error("修改参数项失败！");
            }

            this.$message.success("修改参数项成功！");
        },

        // 删除tag标签
        handleClose(index, row) {
            row.attr_vals.splice(index, 1)
            this.saveAttrVals(row)
        },

        // input框的显示
        showInput(row) {
            // 显示input框
            row.inputVisible = true

            // 让文本框自动获得焦点
            // $nextTick 方法的作用，就是当页面上元素被重新渲染之后，才会执行回调函数中的代码
            this.$nextTick(() => {
                this.$refs.saveTagInput.$refs.input.focus();
            });
        },

        // 关闭添加参数弹窗
        addParamasClosed() {
            this.addParamasVisible = false
        },

        openAddParamas() {
            // 每次打开前清空数据
            // this.addParamasForm.attr_name = ''
            this.addParamasVisible = true

            // 保证页面数据更新好后才能拿到addParamasFormRef
            this.$nextTick(() => {
                this.$refs.addParamasFormRef.resetFields()
            })
        },

        // 添加参数
        addParamas() {
            this.$refs.addParamasFormRef.validate(async valid => {
                if(valid) {
                    const paramas = {
                        attr_name: this.addParamasForm.attr_name,
                        attr_sel: this.activeName,
                        attr_vals: ''
                    }

                    const res = await this.$http.post(`categories/${this.cateId}/attributes`, paramas)

                    console.log(res);

                    if(res.status !== 200) {
                        this.$message.error(res.data.meta.msg)
                        return
                    }

                    this.getParamsData()
                    this.$message.success('创建成功')
                    this.addParamasVisible = false
                }
            })
        },

        // 删除参数
        async removeParams(attrid) {
            const res = await this.$http.delete(`categories/${this.cateId}/attributes/${attrid}`)

            // console.log(res);

            if(res.status == 200) {
                this.getParamsData()
            }
        }
    },

    computed: {
        isBtnDisabled() {
            if (this.selectedCateKeys.length == 3) {
                return false
            }
            return true
        },
        cateId() {
            if (this.selectedCateKeys.length == 3) {
                return this.selectedCateKeys[2]
            }

            return null
        },
    }
}
</script>

<style lang="less" scoped>
.cat_opt {
    margin: 15px 0;
}

.el-tag {
    margin: 10px;
}

.input-new-tag {
    width: 120px;
}
</style>